package framework.view {
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	import framework.model.Box2DWorldModel;
	import framework.signals.RegisterBlitDisplayObjectSignal;
	import org.robotlegs.mvcs.Mediator;

	/**
	 * @author Charlie MacIsaac
	 */
	public class RobotlegsPlaygroundMediator extends Mediator {
		// PROPERTIES =============================================================================
		[Inject]	public var world : Box2DWorldModel;
		
		[Inject]	public var view : RobotlegsPlayground;
		
		[Inject]	public var registerBlitDisplayObjectSignal : RegisterBlitDisplayObjectSignal;
		
		private var _ground : BlitDisplayObjectView;
		private var _circle : BlockView;
		
		// GETTERS + SETTERS ======================================================================
		// CONSTRUCTOR ============================================================================
		public function RobotlegsPlaygroundMediator() { }
		
		// PUBLIC =================================================================================
		override public function onRegister() : void {
			super.onRegister();
			
			contextView.addChild(new BlitCanvasView());
			contextView.addChild(new Profiler());
			
			createGround();
		}
		
		// PRIVATE ================================================================================
		private function createGround() : void {
			registerBlitDisplayObjectSignal.add(groundLoaded);
			_ground = new BlitDisplayObjectView("GroundSkin");
			mediatorMap.createMediator(_ground);
		}
		
		private function createCircle() : void {
			var circleID : uint = world.createCircle(32);
			mediatorMap.createMediator(new BlockView("CircleSkin", circleID));
			view.buttonPressedSignal.add(updateModel);
			view.buttonReleasedSignal.add(updateModel);
		}
		
		// LISTENERS ==============================================================================
		private function groundLoaded(blitDisplayObjectToRegister : BlitDisplayObjectView) : void {
			if (blitDisplayObjectToRegister == _ground) {
				// Remove listener
				registerBlitDisplayObjectSignal.remove(groundLoaded);
				// Set up world
				world.init(_ground.height, view.stage.width, view.stage.height);
				// Position ground
				_ground.y = view.stage.height - _ground.height;
				
				createCircle();
			}
		}
		private function updateModel(e : KeyboardEvent) : void {
			var pressed : Boolean = Boolean(e.type == KeyboardEvent.KEY_DOWN);
			var movement : Number = e.keyCode == Keyboard.RIGHT ? 1 : -1;
			var noMovement : uint = 0;
			
			if (pressed) 	world.moveCircle(movement);
			else 			world.moveCircle(noMovement);
		}
	}
}